<?php

namespace app\services;

use app\extensions\XUtils;
use app\models\Admin;
use app\models\AdminLogger;
use yii;

/**
 * adminService类
 * @author administrate
 * @since 2017-7-10
 */
class AdminService
{
    public function __construct()
    {
        
    }

    /**
     * 登录日志记录
     * @param array $data
     * @return bool
     */
    public function traceLog($data = [])
    {
        $adminLoggerModel = new AdminLogger();
        $result           = $adminLoggerModel->dbAdd($data);
        if ($result == false) {
            echo "日志插入失败 \n";
            foreach ($result->getMessages() as $message) {
                echo $message, "\n";
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * 密码进行加密
     * @param $username
     * @param $password 密码明文
     * @return string
     */
    public function hashPassword($username, $password)
    {
        return md5(md5($username) . md5($password) . Yii::$app->params['adminKeySalt']);
    }

    /**
     * 检查后台用户是否有效
     * @param $username
     * @param $password
     * @return array
     */
    public function isAdminValid($username, $password)
    {
        $result     = [];
        $adminModel = new Admin();
        $res        = $adminModel->dbGet('*', '', ['where' => ['and', 'userName=:userName'], 'bind' => [':userName' => $username]]);
        if ($res['id'] > 0 && $res['password'] == $this->hashPassword($username, $password)) {
            $result['isAdmin'] = true;
            $result['info']    = $res;
        } else {
            $result['isAdmin'] = false;
            $result['info']    = [];
        }
        return $result;
    }

    /**
     * 检查用户是否是后台用户
     * @param $username
     * @return mixed
     */
    public function isAdminUser($username)
    {
        $adminModel = new Admin();
        $res        = $adminModel->dbGet('*', '', ['where' => ['and', 'userName=:userName'], 'bind' => [':userName' => $username]]);
        return $res;
    }

    /**
     * 记录登录的session并更新相关数据
     * @param $data
     * @return bool
     */
    public function login($data)
    {
        $adminModel = new Admin();
        Yii::$app->session->set('_adminiGroupId', $data['groupId']);
        Yii::$app->session->set('_adminiUserId', $data['id']);
        Yii::$app->session->set('_adminiUserName', $data['userName']);
        Yii::$app->session->set('_adminiRealName', $data['realName']);
        $params     = [
            'where' => "id={$data['id']}"
        ];
        $updateData = [
            'lastLoginIp'   => XUtils::getClientIP(),
            'loginCount'    => $data['loginCount'] + 1,
            'lastLoginTime' => time(),
        ];
        $affect     = $adminModel->dbUpdate('', $updateData, $params);
        return $affect;
    }

    /**
     * 通过用户ID查找今天内用户登录出错的次数
     * @param $userId
     * @return array
     */
    public function getTodayLoginErrorCountByUserId($userId)
    {
        $adminLoggerModel = new AdminLogger();
        $startTime        = strtotime(date('Y-m-d') . ' 00:00:00');
        $endTime          = strtotime(date('Y-m-d') . ' 23:59:59');
        $condition        = [
            'where' => [
                'and',
                ['>=', 'createTime', $startTime],
                ['<=', 'createTime', $endTime],
                "`catalog`='login_pass_error'",
                'userId' => $userId,
            ]
        ];
        $count            = $adminLoggerModel->dbCount($condition);
        return $count;
    }

    /**
     * 通过用户ID更新用户组为禁用
     * @param $userId
     */
    public function updateUserGroupForbiddenByUserId($userId)
    {
        $adminModel = new Admin();
        $params     = [
            'where' => "id={$userId}"
        ];
        $updateData = ['groupId' => '2'];
        $adminModel->dbUpdate('', $updateData, $params);
    }

    /**
     * 插入日志记录
     * @param $intro
     * @param $userId
     * @param $userName
     * @param string $catalog
     * @return bool
     */
    public function insertTraceLog($intro, $userId, $userName, $catalog = 'login')
    {
        $ip     = XUtils::getClientIP();
        $result = $this->traceLog(['catalog' => $catalog, 'userId' => $userId, 'intro' => $intro . json_encode($userName), 'createTime' => time(), 'url' => '/admin/public/login', 'ip' => $ip]);
        return $result;
    }

    /**
     * 通过session获取登录用户用户名
     * @return int|mixed
     */
    public static function getLoginUserNameFromSession()
    {
        $userName = Yii::$app->session->get('_adminiUserName');
        return $userName ? $userName : 0;
    }

    /**
     * 通过session获取登录用户真实姓名
     * @return int|mixed
     */
    public static function getLoginRealNameFromSession()
    {
        $realName = Yii::$app->session->get('_adminiRealName');
        return $realName ? $realName : 0;
    }

    /**
     * 通过session获取登录用户ID
     * @return int|mixed
     */
    public static function getLoginUserIdFromSession()
    {
        $userId = Yii::$app->session->get('_adminiUserId');
        return $userId ? $userId : 0;
    }

    /**
     * 通过session获取登录用户组ID
     * @return int|mixed
     */
    public static function getLoginGroupIdFromSession()
    {
        $groupId = Yii::$app->session->get('_adminiGroupId');
        return $groupId ? $groupId : 0;
    }

    /**
     *用户退出时移除相关session
     */
    public static function removeUserLoginSession()
    {
        Yii::$app->session->remove('_adminiUserName');
        Yii::$app->session->remove('_adminiRealName');
        Yii::$app->session->remove('_adminiUserId');
        Yii::$app->session->remove('_adminiGroupId');
    }

    /**
     * 通过用户名和邮箱查找用户数据
     * @param $userName
     * @param $email
     * @return mixed
     */
    public function checkUserByUserNameAndEmail($userName, $email)
    {
        $conditions = [
            'where' => [
                'AND',
                'userName=:userName',
                'email=:email'
            ],
            'bind'  => [
                ':userName' => $userName,
                ':email'    => $email
            ]
        ];
        $adminModel = new Admin();
        $result     = $adminModel->dbGet('*', '', $conditions);
        return $result;
    }

    /**
     * 通过条件查询后台用户数据
     * @param $condition 示例如下 注意：要求key要和数据库中的字段对应 才能使用此方法
     * $conditions = [
     * "id"    => $id,
     * "email" => $email
     * ]
     * @return mixed
     */
    public function checkUserByCondition($condition)
    {
        $param = [
            'where' => [
                'AND',
            ],
            'bind'  => [
            ]
        ];
        foreach ($condition as $key => $value) {
            $param['where'][]       = "$key=:$key";
            $param['bind'][":$key"] = $value;
        }
        $adminModel = new Admin();
        $result     = $adminModel->dbGet('*', '', $param);
        return $result;
    }

    /**
     * 判断用户组是否存在
     * @param $userName
     * @param int $userId
     * @return bool
     */
    public function checkUserNameIsExists($userName, $userId = 0)
    {
        $adminModel = new Admin();
        $param      = [
            'where' => [
                'and',
                'userName=:userName'
            ],
            'bind'  => [
                ':userName' => $userName
            ]
        ];
        if ($userId) {
            $param['where'][]     = 'id!=:id';
            $param['bind'][':id'] = $userId;
        }
        $userCheck = $adminModel->dbGet('*', '', $param);
        if (!empty($userCheck)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除用户组数据
     * @param $id
     * @return mixed
     */
    public static function deleteUser($id)
    {
        $adminModel = new Admin();
        $param      = [
            'where' => [
                'and',
                'id=:id'
            ],
            'bind'  => [
                ':id' => $id
            ]
        ];
        $check      = $adminModel->dbGet('*', '', $param);
        if (empty($check)) {
            $return['code']    = 1001;
            $return['message'] = '找不到相关数据';
        } else {
            try {
                $result = $adminModel->dbDel('', ['where' => 'id=:id', 'bind' => [':id' => $id]]);
                if ($result) {
                    $return['code']    = 1000;
                    $return['message'] = '删除成功!';
                } else {
                    $return['code']    = 1001;
                    $return['message'] = '删除失败!';
                }
            } catch (Exception $e) {
                $return['code']    = 1001;
                $return['message'] = '数据删除失败';
            }
        }
        return $return;
    }
}
